package com.hxg.security;

import com.hxg.core.properties.SecurityProperties;
import com.hxg.rbac.bean.Admin;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.social.security.SocialUserDetails;
import org.springframework.social.security.SocialUserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@Transactional
@Slf4j
public class DemoUserDetailsService implements UserDetailsService, SocialUserDetailsService {

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private SecurityProperties securityProperties;

    /*
     * (non-Javadoc)
     *
     * @see org.springframework.security.core.userdetails.UserDetailsService#
     * loadUserByUsername(java.lang.String)
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户登录:" + username);

        return buildUser(username);
    }

    @Override
    public SocialUserDetails loadUserByUserId(String username) throws UsernameNotFoundException {
        log.info("社交登录:" + username);

        return buildUser(username);
    }

    private SocialUserDetails buildUser(String username) {
        // 123456便为从数据库中获取得到的密码，这里就不链接数据库了
        String password = passwordEncoder.encode("123456");

        Admin admin = new Admin(username, password,
                true, true, true, true,
                AuthorityUtils.commaSeparatedStringToAuthorityList("all,ROLE_USER"));

        admin.setId(1l);

        return admin;
    }

}
